﻿KISSY.add("fgt/core/ajax/loading", function (S) {
    function Loading(block, config) {
        var self = this;
        if (S.isString(block)) {
            block = S.all(block);
        }

        if (!block) {
            S.log("请配置正确的block ID.", "error");
            return;
        }

        self._init(block, config || {});
    }

    S.augment(Loading, {
        _init: function (block, config) {
            var self = this;

            self.block = block;
            self.config = S.merge(
            {
                refresh: false,
                loadingHtml: "<div class='loading' style='width: 100%; height: 200px;'><div class='text'><span>加载中...</span></div></div>",
                loadFailureHtml: ""
            }, config);
        },

        load: function () {
            var self = this,
                J = jQuery,
                block = self.block,
                config = self.config,
                refresh = config.refresh,
                url = config.url;

            if ((refresh && !block.hasClass("loading")) || (!block.hasClass("loading") && !block.hasClass("loaded"))) {
                var resultCode = FGT.core.constant.jsonResultCode;
                if (url) {
                    J.ajax({
                        url: url,
                        type: "GET",
                        cache: false,
                        beforeSend: function (jqXHR, settings) {
                            var b = block;
                            b.empty();
                            b.append(config.loadingHtml);
                            b.addClass("loading");
                        },
                        success: function (data, textStatus, jqXHR) {
                            var b = block;
                            if (data.Result === resultCode.SUCCESS) {
                                b.empty();
                                b.append(data.Content);
                                b.addClass("loaded");
                            }
                            else {
                                b.empty();
                                b.append(config.loadFailureHtml);
                            }
                            b.removeClass("loading");
                        },
                        error: function (jqXHR, textStatus, errorThrown) {
                            var b = block;
                            b.empty();
                            b.append(config.loadFailureHtml);
                            b.removeClass("loading");
                        }
                    });
                }
            }
        }
    });

    return Loading;
});